package com.campus.campusdelivery.service.impl;

import com.campus.campusdelivery.constant.UserRole;
import com.campus.campusdelivery.dto.LoginRequest;
import com.campus.campusdelivery.dto.LoginResponse;
import com.campus.campusdelivery.dto.RegisterRequest;
import com.campus.campusdelivery.entity.DeliveryPerson;
import com.campus.campusdelivery.entity.Merchant;
import com.campus.campusdelivery.entity.User;
import com.campus.campusdelivery.repository.DeliveryPersonRepository;
import com.campus.campusdelivery.repository.MerchantRepository;
import com.campus.campusdelivery.repository.UserRepository;
import com.campus.campusdelivery.service.AuthService;
import com.campus.campusdelivery.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    
    private final UserRepository userRepository;
    private final MerchantRepository merchantRepository;
    private final DeliveryPersonRepository deliveryPersonRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    
    @Override
    public LoginResponse login(LoginRequest request) {
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> new RuntimeException("用户名或密码错误"));
        
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        if (!user.getEnabled()) {
            throw new RuntimeException("账户已被禁用");
        }
        
        String token = jwtUtil.generateToken(user.getUsername(), user.getId(), user.getRole().getCode());
        
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUserRole(user.getRole());
        
        LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRealName(user.getRealName());
        userInfo.setPhone(user.getPhone());
        userInfo.setEmail(user.getEmail());
        userInfo.setAvatar(user.getAvatar());
        response.setUserInfo(userInfo);
        
        return response;
    }
    
    @Override
    @Transactional
    public void register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查手机号是否已存在
        if (userRepository.existsByPhone(request.getPhone())) {
            throw new RuntimeException("手机号已存在");
        }
        
        // 检查邮箱是否已存在
        if (request.getEmail() != null && userRepository.existsByEmail(request.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }
        
        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRealName(request.getRealName());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setRole(request.getRole());
        user.setEnabled(true);
        
        user = userRepository.save(user);
        
        // 根据角色创建相应的实体
        if (request.getRole() == UserRole.MERCHANT) {
            Merchant merchant = new Merchant();
            merchant.setUser(user);
            merchant.setShopName("新店铺");
            merchantRepository.save(merchant);
        } else if (request.getRole() == UserRole.DELIVERY) {
            DeliveryPerson deliveryPerson = new DeliveryPerson();
            deliveryPerson.setUser(user);
            deliveryPersonRepository.save(deliveryPerson);
        }
    }
    
    @Override
    public void logout(String token) {
        // 在实际项目中，可以将token加入黑名单
        // 这里简单实现，客户端删除token即可
    }
}
